package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.service.AddressBookService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Description:
 * @Title: AddressBookServiceImpl
 * @Package com.itheima.reggie.service.impl
 * @Author: 🐟
 * @Copyright 🐟
 * @CreateTime: 2022/9/15 21:30
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
   @Autowired
   private UserService userService;
   @Autowired
   private AddressBookService addressBookService;
   @Autowired
   private HttpSession session;


    @Override
    public void addAddress(AddressBook addressBook, HttpServletRequest request) {
        Long id = (Long) request.getSession().getAttribute("User");
        addressBook.setUserId(id);

        addressBookService.save(addressBook);
    }

    @Override
    public void setdefault(AddressBook addressBook) {
        Long id = addressBook.getId();
        AddressBook byId = addressBookService.getById(id);
        Long userId = byId.getUserId();
        LambdaUpdateWrapper<AddressBook> lqw = new LambdaUpdateWrapper<>();
        lqw.set(AddressBook::getIsDefault,0);
        lqw.eq(AddressBook::getUserId,userId);
        addressBookService.update(lqw);
        LambdaUpdateWrapper<AddressBook> lqw2 = new LambdaUpdateWrapper<>();
        lqw2.set(AddressBook::getIsDefault,1);
        lqw2.eq(AddressBook::getId,id);
        addressBookService.update(lqw2);
    }

    @Override
    public AddressBook getAddressBookByIdAndis_default() {
        Long user = (Long) session.getAttribute("User");
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,user).eq(AddressBook::getIsDefault,1);
        AddressBook one = addressBookService.getOne(lqw);
        return one;
    }
}
